﻿using System;
using System.Threading.Tasks;
using System.Transactions;
using WalkingTec.Mvvm.Core;
using HengTong.Model.Db;
using HengTong.Model.Db.Hr;
using UUIDNext;


namespace HengTong.ViewModel.Hr.SysHrInterviewPoolVms
{
    public partial class SysHrInterviewPoolVm : CrudVm<SysHrInterviewPool>
    {

        public SysHrInterviewPoolVm()
        {
            SetInclude(x => x.InterviewRequestBill);
        }

        protected override void InitVM()
        {
        }

        public override async Task DoAddAsync()
        {
            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }
            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }
            await base.DoEditAsync(updateAllFields);
        }
        
        /// <summary>
        /// 必须使用异步事务, 否则工作流引擎会和当前事务冲突
        /// </summary>
        /// <param name="upAllFields"></param>
        public async Task ApproveAsync(bool upAllFields = false)
        {
            using var transactionScope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(10) // 增加超时时间到10分钟
                },
                TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    await ContinueWorkflowAsync(ActionName, Remark);
                    if (MSD.IsValid)
                    {
                        transactionScope.Complete(); // 提交事务
                    }
                }
                // 如果到这里，事务会自动回滚
            }
            catch (Exception e)
            {
                // TransactionScope会自动回滚，无需手动操作
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
        }
        

        public override void DoDelete()
        {
            base.DoDelete();
        }
    }
}
